package glue_datasyncer

import (
	"fmt"
	"github.com/kataras/iris/v12"
	"github.com/wutianze/nats.go"
	streamCtx "gluenet/internal/glue-datasyncer/context"
	"gluenet/internal/glue-datasyncer/jaeger"
	"gluenet/internal/glue-datasyncer/logs"
	"gluenet/internal/glue-datasyncer/metrics"
	"gluenet/internal/glue-datasyncer/rule"
	"gluenet/internal/glue-datasyncer/socket"
	"gluenet/internal/glue-datasyncer/trace"
	"gluenet/pkg/apis"
	"gluenet/pkg/nets"
	v1 "gluenet/utils/rpc/labels"
	"net/http"
)

// port 10001
var natsRouter = [][2]interface{}{
	{v1.ControlManager + ":" + v1.TracePush, trace.Traces},
	{v1.ControlManager + ":" + v1.MetricsPush, metrics.Metrics},
	{v1.ControlManager + ":" + v1.LogPush, logs.Logs},
}

// port 10001
var httpRouter = [][2]interface{}{
	{apis.MetricsWrite, ReciverMetricsStream},
	//{apis.LogsWrite,ReciverMetricsStream},
}

// port 10000
var appRouter = [][3]interface{}{
	//{"GET", apis.PrometheusProxy, proxy.ProxyPrometheusQuery},
	{"GET", apis.Socket, socket.Socket},
	{"GET", apis.SocketList, socket.SocketList},
	{"POST", apis.PutRules, rule.PutRules},
	{"GET", apis.GetRules, rule.GetRules},
	{"GET", apis.GetAlert, rule.GetAlert},
	{"POST", apis.PutRulesV2, rule.PutRulesV2},
	{"GET", apis.MonitorGetInstanceLogsCounts, logs.LogsCount},
	{"GET", apis.MonitorGetInstanceLogsInfo, logs.LogsInfoList},
	{"GET", apis.MonitorGetInstanceLogsInfoSocket, logs.LogsSocket},
	{"GET", apis.MonitorGetJaegerSearch, jaeger.JaegerSearch},
}

func Register(ctx *streamCtx.StreamContext) {
	handler := http.NewServeMux()
	for _, v := range httpRouter {
		route := v[0].(string)
		handle := v[1].(func(*streamCtx.StreamContext))
		handler.HandleFunc(route, func(writer http.ResponseWriter, request *http.Request) {
			g := *ctx
			g.ResponseWriter = writer
			g.ResquestReader = request
			handle(&g)
		})
		ctx.Logger.Debugf("register http service %v %v", route, handle)
	}
	ctx.ReciverServer.Handler = handler

	party := ctx.AppServer.Party("/", func(ctx iris.Context) {
		fmt.Printf("auth .....\n")
		//token := ctx.GetHeader("token")
		//if err := login.Auth(token); err != nil {
		//	ctx.JSON(infra.ResponseReqErr(err, nil))
		//	return
		//}
		ctx.Values().Set("user_id", "user1")
		ctx.Next()
	})
	for _, v := range appRouter {
		method := v[0].(string)
		route := v[1].(string)
		handle := v[2].(func(*streamCtx.StreamContext))
		party.Handle(method, route, func(c iris.Context) {
			c.Header("Set-Cookie", "SameSite=None; Secure")
			c.Header("x-frame-options", "SAMEORIGIN")
			g := *ctx
			g.WebContext = c
			handle(&g)
		})
		ctx.Logger.Debugf("register http service %v %v", route, handle)
	}
	for _, v := range natsRouter {
		topic := v[0].(string)
		handle := v[1].(func(*streamCtx.StreamContext))
		if _, err := ctx.Nats.Subscribe(topic, func(msg *nats.Msg) {
			ct := *ctx
			ct.RpcContext = &nets.NetContext{
				Data: msg,
			}
			handle(&ct)
		}); err != nil {
			ctx.Logger.Fatalf("register nats service %v %v", topic, handle)
		}
	}
}
